/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.asu.cse360.service.impl;

import edu.asu.cse360.dto.ItemEfficiency;
import edu.asu.cse360.dto.ItemEfficiencyReport;
import edu.asu.cse360.model.ItemOrder;
import edu.asu.cse360.model.MenuItem;
import edu.asu.cse360.model.Restaurant;
import edu.asu.cse360.service.ItemOrderService;
import edu.asu.cse360.service.ItemReportService;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("itemReportService")
public class ItemReportServiceImpl implements ItemReportService{
    
    @Autowired
    private ItemOrderService itemOrderService;

    @Override
    public ItemEfficiencyReport getEfficiencyReport(Restaurant restaurant, DateTime start, DateTime end) {
        List<ItemOrder> itemOrders = itemOrderService.getItemOrders(restaurant, start, end);
        List<ItemEfficiency> itemEfficiencies = getEfficiencies(itemOrders);
        return new ItemEfficiencyReport(itemEfficiencies);
    }

    private List<ItemEfficiency> getEfficiencies(List<ItemOrder> itemOrders) {
        Map<MenuItem, Integer> itemEfficiencyMap = createEfficienyMap(itemOrders);
        return getItemEfficiencies(itemEfficiencyMap);
    }

    private Map<MenuItem, Integer> createEfficienyMap(List<ItemOrder> itemOrders) {
        Map<MenuItem, Integer> itemEfficiencyMap = new LinkedHashMap<MenuItem, Integer>();
        for(ItemOrder itemOrder : itemOrders){
            MenuItem menuItemKey = itemOrder.getMenuItem();
            Integer frequency = itemEfficiencyMap.get(menuItemKey);
            if(frequency == null){
                itemEfficiencyMap.put(menuItemKey, 1);
            }else{
                itemEfficiencyMap.put(menuItemKey, frequency + 1);
            }
        }
        return itemEfficiencyMap;
    }

    private List<ItemEfficiency> getItemEfficiencies(Map<MenuItem, Integer> itemEfficiencyMap) {
        List<ItemEfficiency> itemEfficiencies = new ArrayList<ItemEfficiency>();
        for(MenuItem item : itemEfficiencyMap.keySet()){
            Integer frequency = itemEfficiencyMap.get(item);
            itemEfficiencies.add(new ItemEfficiency(item, frequency));
        }
        return itemEfficiencies;
    }

}
